﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using ORM.Attribute;

namespace ORM
{
    public class ProcHelper<T>  where T : ITableObject, new ()
    {
        public int Add(T t, ref string outParas)
        {
            string strconn = "Data Source=.;Initial Catalog=taoka;Persist Security Info=True;User ID=sa;";
            int iResult = 0;
            string str = "";
            SqlConnection conn = null;
            try
            {
                using (conn = new SqlConnection(strconn))
                {
                    conn.Open();
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "proc_Customer_add";
                    cmd.CommandTimeout = 30;
                    SqlParameter[] paras = GetSqlParameter(t, DbAction.insert);
                    cmd.Parameters.AddRange(paras);

                    iResult = cmd.ExecuteNonQuery();
                    foreach (SqlParameter sqlParameter in paras)
                    {
                        if (sqlParameter.Direction == ParameterDirection.Output)
                            str += "," + sqlParameter.Value; 
                    }
                    outParas = str.Trim(',');
                    cmd.Dispose();
                }
            }
            catch (Exception ex)
            {
                outParas = ex.Message;
            }
            finally
            {
                if(null != conn && conn.State ==ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }

            }
            return iResult;
        }


        /// <summary>
        /// 获取指定对象，指定操作下的SqlParameter数组
        /// </summary>
        /// <typeparam name="T">T类型</typeparam>
        /// <param name="t">T对象实例</param>
        /// <param name="action">操作类型(insert, delete, update, select)</param>
        /// <returns>SqlParameter数组</returns>
        private SqlParameter[] GetSqlParameter(T t, DbAction action)
        {
            PropertyInfo[] infos = typeof(T).GetProperties();
            FieldAttribute fieldAttr;
            object objValue = null;
            List<SqlParameter> list = new List<SqlParameter>();

            foreach (PropertyInfo info in infos)
            {
                objValue = AttributeHelper.GetPropertyValue<T>(t, info.Name);
                fieldAttr = AttributeHelper.GetPropertyAttribute(info);
                if (null == fieldAttr) continue;
                if(String.IsNullOrEmpty(fieldAttr.FieldName)) continue;
                if (action == DbAction.insert && !fieldAttr.IsInsert) continue;
                if (action == DbAction.update && !fieldAttr.IsUpdate) continue;
     
                SqlParameter para = new SqlParameter(String.Format("@{0}", fieldAttr.FieldName),
                                                     TypeParseHelper.ParseType(fieldAttr.FieldType));
                para.Direction = ParameterDirection.Input;
                para.Value = objValue ?? "";
                list.Add(para);
            }
            
            return list.ToArray();
        }
    }
}
